var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken');
const {verifyToken , judgeToken , decodeToken} = require('../../tool/jwt')
const {setDate} = require('../../tool/date')


module.exports = (pool) => {

//验证token方法
const tokenvalidate = (req,res,next)=>{
  try {
    const token = req.headers.token;
    const v = verifyToken(token,'shop_key')
    if(v != null){
      const v2 = judgeToken(token,'shop_key')
      if(v2 ==0){
        next()
      }else{
        return res.send({data:{msg:'token已过期',code:'500'}})
      }

    }else{
      return res.send({data:{msg:'token已过期',code:'500'}})
    }
    
  } catch (error) {
    console.log(error)
    res.status(500).send('Error');
    process.exit(1)
  }
}



//登入
router.post('/login', async (req, res, next) =>{
  res.setHeader('Access-Control-Allow-Origin','*')
  if(!req.body.username){
    return res.send({data:{msg:"用户名不能为空",code:'500'}});
  }
  if(!req.body.password) {
    return res.send({data:{msg:"密码不能为空",code:'500'}});
  }
  next();
},async (req,res)=>{
  try {
    const {username,password} = req.body
    
    const connection = await pool.promise().getConnection()
    var user = await connection.query(`select * from admin where username= ?`,username)
    connection.release()
    if(user[0].length !== 0){
      if(user[0][0].password == password){
        const token = generateToken(user[0][0])
        return res.send({data:{msg:"登入成功",code:'200',token:token}});
        }else{
        return res.send({data:{msg:"密码错误",code:'500'}});
      }
    }else{
      return res.send({data:{msg:"用户不存在",code:'500'}});
    }

  } catch (error) {
    console.log(error)
    res.status(500).send({data:{msg:"服务异常",code:500}});
  }
})


  

//生成token
function generateToken(user) {
  const payload = {
    username: user.username,
    id: user.id,
    state: user.state,
    login_date: user.login_date
  };
  const secretKey = 'shop_key'
  const options = {
    expiresIn: '7d' 
  };
  const token = jwt.sign(payload, secretKey, options);
  return token;
}



  //返回路由
  return router

}

